﻿
Imports osi.root.utils
Imports osi.root.delegates
Imports osi.root.connector
Imports osi.root.formation
Imports osi.root.lock

Public Module _async_model
    Public Function begin(ByVal action As callback_action) As Boolean
        Return callback_manager.global.begin(action)
    End Function

    Public Sub assert_begin(ByVal action As callback_action)
        assert(begin(action))
    End Sub

    Public Function begin(ByVal action As callback_action, ByVal timeout_ms As Int64) As Boolean
        Return callback_manager.global.begin(action, timeout_ms)
    End Function

    Public Sub assert_begin(ByVal action As callback_action, ByVal timeout_ms As Int64)
        assert(begin(action, timeout_ms))
    End Sub

    Public Function begin(ByVal ec As event_comb, ByVal timeout_ms As Int64) As Boolean
        Return event_driver.global.begin(ec, timeout_ms)
    End Function

    Public Function begin(ByVal ec As event_comb) As Boolean
        Return event_driver.global.begin(ec)
    End Function

    Public Sub assert_begin(ByVal ec As event_comb, ByVal timeout_ms As Int64)
        assert(begin(ec, timeout_ms))
    End Sub

    Public Sub assert_begin(ByVal ec As event_comb)
        assert(begin(ec))
    End Sub

    Public Sub begin_lifetime_event_comb(ByVal stopping As _do(Of Boolean),
                                         ByVal ParamArray d() As _do(Of Boolean))
        assert(Not stopping Is Nothing)
        Dim d2() As _do(Of Boolean) = Nothing
        ReDim d2(array_size(d))
        For i As Int32 = 0 To array_size(d) - 1
            Dim j As Int32 = 0
            j = i
            d2(i) = Function() As Boolean
                        If stopping() Then
                            Return goto_end()
                        Else
                            Return d(j)()
                        End If
                    End Function
        Next
        Dim ec As event_comb = Nothing
        d2(array_size(d)) = Function() As Boolean
                                If stopping() Then
                                    Return goto_end()
                                Else
                                    Return goto_begin()
                                End If
                            End Function
        ec = New event_comb(d2)
        assert_begin(ec)
    End Sub

    Public Sub begin_lifetime_event_comb(ByVal lifetime As wrapper(Of singleentry),
                                         ByVal ParamArray d() As _do(Of Boolean))
        assert(Not lifetime Is Nothing)
        begin_lifetime_event_comb(Function() lifetime.in_use(), d)
    End Sub

    Public Sub begin_application_lifetime_event_comb(ByVal ParamArray d() As _do(Of Boolean))
        begin_lifetime_event_comb(Function() application_lifetime.stopping(), d)
    End Sub
End Module
